package com.banciyuan.bcywebview.biz.pc;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.banciyuan.bcywebview.R;
import com.banciyuan.bcywebview.api.GroupApi;
import com.banciyuan.bcywebview.base.fragment.BaseLazyContainerFragment;
import com.banciyuan.bcywebview.base.helper.ProgressbarHelper;
import com.banciyuan.bcywebview.base.helper.data.UserDataHelper;
import com.banciyuan.bcywebview.base.view.pulltorefresh.PullToRefreshBase;
import com.banciyuan.bcywebview.base.view.pulltorefresh.PullToRefreshListView;
import com.banciyuan.bcywebview.biz.groupdetail.NewTeamDetailActivity;
import com.banciyuan.bcywebview.biz.main.group.groupselect.GroupSelectActivity;
import com.banciyuan.bcywebview.biz.main.group.hot.GroupHotAdapterSearch;
import com.banciyuan.bcywebview.utils.http.BcyPair;
import com.banciyuan.bcywebview.utils.http.HttpUtils;
import com.banciyuan.bcywebview.utils.http.OnErrorProxy;
import com.banciyuan.bcywebview.utils.http.StatusCodeUtils;
import com.banciyuan.bcywebview.utils.http.StringRequestParam;
import com.banciyuan.bcywebview.utils.http.VolleyQueue;
import com.banciyuan.bcywebview.utils.intent.gotoUtil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import de.greenrobot.daoexample.model.TagDetail;
import de.greenrobot.daoexample.model.Team;


public class TeamsFragment extends BaseLazyContainerFragment implements View.OnClickListener {
    private RequestQueue queue;
    private List<Team> mData = new ArrayList<>();
    private String uid;
    private int page = 1;
    private PullToRefreshListView refreshListView;
    private ListView lv;
    private GroupHotAdapterSearch adatper;
    private ProgressbarHelper mProgressbarHelper;
    private View mProgressbarView;
    private boolean loading = false;
    private boolean is_end = false;
    private View emptyView;
    private boolean preLoad;

    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View viewroot = inflater.inflate(R.layout.activity_teams_list, container, false);
        initArgs();
        initProgressbar(viewroot);
        initUi(viewroot);
        initAction();
        if (preLoad)
            getFocusedGroup();
        return viewroot;
    }

    @Override
    public void fetchData() {
        getFocusedGroup();
    }

    @Override
    protected void initProgressbar(View rootview) {
        mProgressbarView = rootview.findViewById(R.id.base_progressbar);
        mProgressbarHelper = new ProgressbarHelper(mProgressbarView);
        mProgressbarHelper.setActionCallbacks(new ProgressbarHelper.OnProgressCallbacks() {
            @Override
            public void onActionClick(int id) {
                if (!loading) {
                    loading = true;
                    mProgressbarHelper.onLoading();
                    page = 1;
                    mData.clear();
                    getFocusedGroup();
                }
            }
        });
        mProgressbarHelper.onLoading();
    }


    private void getFocusedGroup() {
        List<BcyPair> paramsList = new ArrayList<BcyPair>();
        paramsList.add(new BcyPair(HttpUtils.TOKEN, UserDataHelper.getInstance(getActivity()).getToken()));
        paramsList.add(new BcyPair(HttpUtils.UID, uid));

        paramsList.add(new BcyPair(HttpUtils.INDEX_P, page + ""));
        paramsList.add(new BcyPair(HttpUtils.LIMIT, "10"));

        final HashMap<String, String> params = HttpUtils.getData(paramsList);
        final String url = HttpUtils.BASE_URL + GroupApi.getFocusedgroup();

        Response.Listener onSucc = new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                if (StatusCodeUtils.dealStatusCode(s, getActivity())) {
                    try {
                        JSONObject obj = new JSONObject(s);
                        JSONArray resultArray = obj.getJSONArray("data");
                        Gson gson = new Gson();
                        List<Team> templist = gson.fromJson(resultArray.toString(), new TypeToken<List<Team>>() {
                        }.getType());
                        if (!templist.isEmpty()) {
                            setWorkToTag(templist);
                            dealJson(templist);
                        } else {
                            if (page == 1) {
                                emptyView.setVisibility(View.VISIBLE);
                                mProgressbarHelper.onSuccess();
                                refreshListView.onRefreshComplete();
                            } else {
                                emptyView.setVisibility(View.GONE);
                                mProgressbarHelper.onSuccess();
                                refreshListView.onRefreshComplete();
                            }
                            is_end = true;
                        }
                    } catch (Exception e) {
                        onError();
                    }
                }
            }
        };

        Response.ErrorListener onError = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                onError();
            }
        };

        OnErrorProxy errorProxy = new OnErrorProxy(onError, onSucc, url, getActivity(), params);
        StringRequestParam requestParam = new StringRequestParam(Request.Method.POST, url, params, onSucc, errorProxy);
        queue.add(requestParam);
    }

    private void onError() {
        loading = false;
        emptyView.setVisibility(View.GONE);
        mProgressbarHelper.onFailed();
        refreshListView.onRefreshComplete();
    }

    private void setWorkToTag(List<Team> templist) {
        for (Team h : templist) {
            if (!TextUtils.isEmpty(h.getWork())) {
                TagDetail tagDetail = new TagDetail();
                tagDetail.setWork(h.getWork());
                tagDetail.setWid(h.getId());
                tagDetail.setTag_name(h.getWork());
                h.getTags().add(0, tagDetail);
            }
        }
    }

    private void dealJson(List<Team> tlist) {
        if (page == 1) {
            mData.clear();
        }
        mData.addAll(tlist);
        if (adatper == null) {
            adatper = new GroupHotAdapterSearch(getActivity(), mData);
            lv.setAdapter(adatper);
        } else {
            adatper.notifyDataSetChanged();
        }
        onSucc();
    }

    private void onSucc() {
        loading = false;
        emptyView.setVisibility(View.GONE);
        mProgressbarHelper.onSuccess();
        refreshListView.onRefreshComplete();
    }


    @Override
    protected void initUi(View rootview) {
        emptyView = rootview.findViewById(R.id.layout_empty);
        emptyView.setVisibility(View.GONE);
        refreshListView = (PullToRefreshListView) rootview.findViewById(R.id.team_refresh_lv);
        lv = refreshListView.getRefreshableView();
        lv.setAdapter(adatper);
        rootview.findViewById(R.id.tv_go_order_team).setOnClickListener(this);
    }

    @Override
    protected void initArgs() {
        queue = VolleyQueue.getRquest(getActivity());
        Bundle bundle = getArguments();
        uid = bundle.getString("uid");
        preLoad = bundle.getBoolean("preLoad");
    }

    @Override
    protected void initAction() {
        refreshListView.setOnLastItemVisibleListener(new PullToRefreshBase.OnLastItemVisibleListener() {
            @Override
            public void onLastItemVisible() {
                if (!loading && !is_end) {
                    page++;
                    loading = true;
                    getFocusedGroup();
                }

            }
        });
        refreshListView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ListView>() {
            @Override
            public void onRefresh(PullToRefreshBase<ListView> refreshView) {
                loading = false;
                is_end = false;
                page = 1;
                getFocusedGroup();
            }
        });

        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                int index = i - 1;
                if (index < 0 || index >= mData.size()) return;
                gotoUtil.gotoAct(getActivity(), NewTeamDetailActivity.class, mData.get(index).getGid(), mData.get(index).getName());
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_go_order_team:
                gotoUtil.gotoAct(getActivity(), GroupSelectActivity.class, 0);
                break;
        }
    }
}
